﻿using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate;
using NHibernate.Linq;
using InnovTech.Data.DataAccess;

namespace InnovTech.Data.NHibernate
{
    public abstract class NHDao<T> : IDao<T> where T : IEntity
    {
        

        public T Get(long id)
        {
            return Session.Get<T>(id);
        }

        public T Get(Func<T, bool> predicate)
        {
            return GetList(predicate).SingleOrDefault();
        }

        public IEnumerable<T> GetList(Func<T, bool> predicate)
        {
            return Session.Query<T>().Where(predicate);
        }

        public void Save(T objToSave)
        {
            Session.SaveOrUpdate(objToSave);
        }

        public void Delete(T objToDelete)
        {
            Session.Delete(objToDelete);
        }

        public void Detach(T obj)
        {
            Session.Evict(obj);
        }

        public object Reattach(object obj)
        {
            return Session.Merge(obj);
        }

        protected abstract ISession Session { get; }
    }
}
